import axios from 'axios'
import to from 'await-to-js'
import store from '@/store'
import router from '@/router'
import { updateToken } from '@/api/user'

export const baseURL = 'https://geek.itheima.net'

const instance = axios.create({
  baseURL,
  timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  res => {
    return res.data // 剥去 axios 自动包装的 data外层
  },
  err => {
    // 根据响应的全向判断拦截
    if (err.response && err.response.status === 401) {
      const refresh_token = store.state.user.refresh_token
      console.log('响应拦截', refresh_token)
      if (refresh_token) {
        console.log('尝试刷新 token')
        updateToken(refresh_token)
          .then(res => {
            // console.log('获取新 token', res)
            // tip: 这里 token 未解构
            const {
              data: {
                data: { token },
              },
            } = res
            // console.log('token 2?', token)
            store.commit('user/setToken', token) // 这里 token 访问最近作用域的
            return instance(err.config)
          })
          .catch(err => {
            console.log('无法获取新 token', err)
            router.push(
              '/login?returnUrl=' +
                encodeURIComponent(router.currentRoute.fullPath)
            )
          })
      }
    }
    return Promise.reject(err)
  }
)

// 导出 axios 实例调用接口的函数
export default ({ url, method = 'GET', params, data, headers }) => {
  const promise = instance({ url, method, params, data, headers })
  return to(promise)
}
